package cn.melonlib.authentication.comp.interceptor;

import cn.melonlib.authentication.anno.HttpAuth;
import cn.melonlib.authentication.comp.service.HttpAccountLoginService;
import cn.melonlib.cores.commons.comp.web.ctrl.BasicController;
import cn.melonlib.objects.maps.JsonMap;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.yaml.snakeyaml.constructor.BaseConstructor;

import javax.annotation.Resource;
import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

@Component
public class HttpAuthInterceptor extends ApplicationObjectSupport implements HandlerInterceptor {

    @Resource
    private HttpAccountLoginService accountLoginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getDispatcherType() == DispatcherType.ASYNC) {
            //避免异步请求多次拦截带来的额外开销
            return true;
        }
        String method=request.getMethod();
        //排出掉一些非正常认证的拦截
        if(!List.of("POST","GET").contains(method)){
            return true;
        }
        if (handler instanceof HandlerMethod handlerMethod) {
            HttpAuth httpAuth = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), HttpAuth.class);
            if(Objects.isNull(httpAuth)){
                return true;
            }
            String auth = request.getHeader("Authorization");
            if (accountLoginService.checkAuth(auth)) {
                return true;
            } else {
                response.setCharacterEncoding("utf-8");
                response.setContentType(BasicController.APPLICATION_JSON_UTF8_VALUE);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setHeader("WWW-Authenticate", " Basic realm=\"Valid username and password\"");
                response.getWriter().println(
                        JsonMap.createMap().append("code", HttpServletResponse.SC_UNAUTHORIZED).append("msg", "你无权访问！！").jsonString()
                );
                return false;
            }
        }
        return true;
    }
}
